<script setup lang="ts">
import { computed, ref, reactive } from 'vue'
import type { StyleValue } from 'vue'

import { getAssetsFiles, uploadTaskEventToGA, handleToEggOrLottery } from '@/utils'

import { fetchSignInData, fetchSignInReward } from '@/api/signIn';
import { uploadTaskEventToAdmin } from '@/api/task'

import { useUserStore } from '@/stores/user';

import BiSkeleton from '@/components/bi-skeleton/index.vue'
import BiPopup from '@/components/bi-popup/index.vue'

defineOptions({
    name: 'BiSignin'
})

interface Props {
    type?: string
}

const props = withDefaults(defineProps<Props>(), {
    type: 'normal',    // 弹窗类型 default: normal 可选 blue
})

const emit = defineEmits(['sign'])

const userStore = useUserStore()
const loading = ref(true)
const handleStopLoading = () => {
    loading.value = false
}

const signInday = ref<number>(0)
const signInState = ref<boolean>(false)
const signInPointsMap = reactive<Array<SignIn>>([])
const signInReward = ref<number>(0)
const signInGoldNum = ref<number>(0)
fetchSignInData({ device: userStore.device }).then(res => {
    signInday.value = res.data.data.signDays
    signInState.value = res.data.data.todaySign
    signInPointsMap.push(...res.data.data.rewardSignVOS)
    signInGoldNum.value = signInPointsMap[signInday.value].value
    handleStopLoading()
}).catch(err => {
    throw new Error(err)
})

const handleSetImgOpacity = (day: number): StyleValue => {
    if (signInday.value >= day) {
        return { opacity: '0.5' }
    }
}
const handleSetTimelineIcon = (index: number): string => {

    if (index === 2 || index === 4) {
        return getAssetsFiles('wheat.png')
    }

    if (index === 6) {
        return getAssetsFiles('mow.png')
    }

    return getAssetsFiles('flame.png')

}
const timelineWidth = computed(() => {
    return { '--width': `${(signInday.value / 7) * 100}%` }
})
const handleSetGreetFont = (day: number): StyleValue => {
    if (signInday.value >= day) {
        return {
            color: props.type === 'normal' ? '#6b61ad' : '#1ca4a1'
        }
    }
}

const useTimelineText = (i: number): string => (i + 1 == 1 ? 'Today' : `Day ${i + 1}`)
const signInBtnText = computed(() => signInState.value ? 'Get more' : 'Check-in')

const showSignInRewardPopup = ref(false)
const openSignSuccessPopup = () => {
    showSignInRewardPopup.value = true
}
const handleCheckMoreAd = () => {
    if (signInState.value) {
        handleToEggOrLottery()
        return
    }
    try {
        android.taskShowInter()
    } catch (error) {
        console.log(error)
    }
    fetchSignInReward({ device: userStore.device }).then(res => {
        if (res.data.code === 0) {
            uploadTaskEventToGA('签到领金币')
            uploadTaskEventToAdmin({
                device: userStore.device,
                moduleType: 2,
                eventType: 32
            })
            signInday.value = signInday.value + 1
            signInReward.value = res.data.data
            userStore.info.totalPoints += res.data.data
            emit('sign')
            openSignSuccessPopup()
        }
    })
        .catch(err => {
            throw new Error(err)
        })
}

</script>

<template>
    <div class="sign" :class="{ blue: props.type === 'blue' }">
        <template v-if="props.type === 'normal'">
            <div class="sign-title">Check-In Streak: 0{{ signInday }} Day(s)</div>
        </template>
        <template v-if="props.type === 'blue'">
            <div class="sign-blue">
                <img class="sign-blue-bg" src="@/assets/imgs/popup/sign_title_bg.png" alt="sign_bg">
                <div class="sign-blue-title">Check-In Streak: 0{{ signInday }} Day(s)</div>
                <div class="sign-blue-sub-title">Obtain ${{ signInGoldNum }}</div>
            </div>
        </template>
        <BiSkeleton v-if="loading && props.type === 'normal'" skeleton-type="signin" />
        <ul v-else>
            <li>
                <div class="timeline">
                    <div class="timeline-list">
                        <div class="timeline-list-item" v-for="(item, key) in signInPointsMap">
                            <img :style="handleSetImgOpacity(item.days)" :src="handleSetTimelineIcon(key)" alt="flame"
                                width="25">
                            <span>+{{ item.value }}</span>
                        </div>
                    </div>
                    <div class="timeline_line" :style="timelineWidth">
                        <div class="timeline_line__dot" v-for="item in 7" :key="item"></div>
                    </div>
                    <div class="timeline_date">
                        <span :style="handleSetGreetFont(key + 1)" v-for="(item, key) in 7" :key="item">
                            {{ useTimelineText(key) }}
                        </span>
                    </div>
                </div>
            </li>
            <li>
                <div class="sign-button click-ad" @click="handleCheckMoreAd">
                    <span>{{ signInBtnText }}</span>
                </div>
            </li>
        </ul>
    </div>

    <Teleport to="#app">
        <BiPopup v-model:show="showSignInRewardPopup" rewards-type="flame" :rewards-num="signInReward" @click="handleToEggOrLottery">
        </BiPopup>
    </Teleport>
</template>

<style scoped lang="scss">
@import url(./index.scss);
</style>